package handler

import (
	"context"
	"examination-management/srv/cmd/config"
	"examination-management/srv/cmd/model"
	"examination-management/srv/pkg"
	pb "examination-management/srv/proto"
	"time"
)

func (s *Server) CreateStudent(_ context.Context, in *pb.CreateStudentReq) (*pb.CreateStudentResp, error) {
	var u model.Student
	config.DB.Debug().Where("mobile = ?", in.Mobile).Limit(1).Find(&u)
	if u.Id != 0 {
		return &pb.CreateStudentResp{
			Message: "已注册",
			Code:    10001,
		}, nil
	}
	user := model.Student{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	err := config.DB.Debug().Create(&user).Error
	if err != nil {
		return &pb.CreateStudentResp{
			Message: "注册失败",
			Code:    10002,
		}, nil
	}
	return &pb.CreateStudentResp{
		Message: "注册成功",
		Code:    200,
	}, nil
}
func (s *Server) LoginStudent(_ context.Context, in *pb.LoginStudentReq) (*pb.LoginStudentResp, error) {
	var st model.Student
	config.DB.Debug().Where("mobile = ?", in.Mobile).Limit(1).Find(&st)
	if st.Id == 0 {
		return &pb.LoginStudentResp{
			Message: "未注册",
			Code:    10001,
		}, nil
	}
	if st.Password != pkg.Md5(in.Password) {
		return &pb.LoginStudentResp{
			Message: "密码错误",
			Code:    10002,
		}, nil
	}
	return &pb.LoginStudentResp{
		Message: "登录成功",
		Code:    200,
		Id:      st.Id,
	}, nil
}
func (s *Server) UpdateStudent(_ context.Context, in *pb.UpdateStudentReq) (*pb.UpdateStudentResp, error) {
	var u model.Student
	config.DB.Debug().Where("id = ?", in.Id).Limit(1).Find(&u)
	if u.Id == 0 {
		return &pb.UpdateStudentResp{
			Message: "未登录",
			Code:    10001,
		}, nil
	}
	UIdCard := "xy" + time.Now().Format("20060102150405")
	user := model.Student{
		Id:           in.Id,
		StudentName:  in.StudentName,
		StudentCard:  UIdCard,
		StudentClass: in.StudentClass,
		College:      in.College,
	}
	err := config.DB.Debug().Updates(&user).Error
	if err != nil {
		return &pb.UpdateStudentResp{
			Message: "更新失败",
			Code:    10002,
		}, nil
	}
	return &pb.UpdateStudentResp{
		Message: "更新成功",
		Code:    200,
	}, nil
}
